package com.yuesystem.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yuesystem.common.BaseContext;
import com.yuesystem.common.CustomException;
import com.yuesystem.dto.responsebody.ReplyResponseBody;
import com.yuesystem.entity.Reply;
import com.yuesystem.entity.User;
import com.yuesystem.mapper.ReplyMapper;
import com.yuesystem.service.ReplyService;
import com.yuesystem.service.UserService;
import java.util.List;
import java.util.stream.Collectors;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * 回复接口实现类.
 */
@Service
@Slf4j
public class ReplyServiceImpl extends ServiceImpl<ReplyMapper, Reply> implements ReplyService {
  
  @Autowired
  private UserService userService;
  
  /**
   * 回复评论.
   *
   * @param reply 一级评论
   */
  @Override
  public void replyComment(Reply reply) {
    // 获取回复者的id
    Long userId = BaseContext.getCurrentId();
    reply.setUserId(userId);
    if (reply.getContent().isEmpty()) {
      throw new CustomException("回复内容不能为空");
    } else {
      this.save(reply);
    }
  }
  
  
  /**
   * 根据一级评论id 和 帖子id 找到所有的子评论.
   *
   * @param blogId 帖子id
   * @param parentCommentId 一级评论id
   * @return 子评论
   */
  // 根据一级评论id 和 帖子id 找到对应的所有的子评论
  public List<ReplyResponseBody> getCommentTwo(Long blogId, Long parentCommentId) {
    // 找出该父评论对应下的所有子评论reply，并封装所有的reply成replyDto,放到replyDtoList1集合中
    LambdaQueryWrapper<Reply> queryWrapper1 = new LambdaQueryWrapper<>();
    queryWrapper1.eq(Reply::getParentCommentId, parentCommentId);
    queryWrapper1.eq(Reply::getBlogId, blogId);
    List<Reply> replyList = this.list(queryWrapper1);
    
    // 封装
    List<ReplyResponseBody> replyResponseBodyList = replyList.stream().map((item1) -> {
      ReplyResponseBody replyResponseBody = new ReplyResponseBody();
      BeanUtils.copyProperties(item1, replyResponseBody);
      // 获取回复人id
      Long userId = item1.getUserId();
      User one = userService.getById(userId);
      // 获取回复人用户名
      String userName = one.getUserName();
      
      if (one != null) {
        replyResponseBody.setUserName(userName);
      }
      return replyResponseBody;
      
    }).collect(Collectors.toList());
    
    return replyResponseBodyList;
  }
  
  /**
   * 根据blog的id删除所有和他有关的回复.
   *
   * @param listBlog 帖子
   */
  @Override
  public void deleteByBlog(List<Long> listBlog) {
    LambdaQueryWrapper<Reply> queryWrapper = new LambdaQueryWrapper<>();
    queryWrapper.in(listBlog.size() != 0, Reply::getBlogId, listBlog);
    this.remove(queryWrapper);
  }
  
  
}
